/**
 * author:Administrator
 * date:2015/7/27
 * desc:TODO
 */

'use strict';
var debugLog = require('./function.js').debugLog;
console.log('Load O2O: ' + module.id);

let F = require('./function');
let roleDispatcher = require('./dao/role.js');

var api = {};
exports.api = api;

/**
 * 在权限系统中, 添加一个角色,并设置权限(如果该角色已存在,则覆盖权限)
 * post /o2o_service/role/v1/add
 {
     "roleName": "管理员",
     "permission":{
        "商家管理": ["添加商家","编辑商家"],
        "商家详情": ["商家详情"]
     },
     "act":1
 }
 */
api.add = function*(Env) {
    Env.I = yield F.Init(Env, [1]);
    if (Env.I.errors) {
        return F.returnMsg(400, Env.I.errors.msg, Env.I.errors.level);
    }
    var fields = Env.I;

    let result = yield roleDispatcher.add(fields);
    if (result.error) {
        return F.returnMsg(400, result.error, 3);
    }
    return F.returnMsg(200, 'OK', 3, result);
};

/**
 * 获取某个角色的权限图
 * post /o2o_service/role/v1/permissions
 {
    "roleName": "管理员",
    "act":1
 }
 * @param Env
 */
api.permissions = function*(Env) {
    Env.I = yield F.Init(Env, [1]);
    if (Env.I.errors) {
        return F.returnMsg(400, Env.I.errors.msg, Env.I.errors.level);
    }
    var fields = Env.I;

    let result = yield roleDispatcher.permissions(fields);
    return F.returnMsg(200, 'OK', 3, result);
};

/**
 * 查询某个角色是否有 指定的单个权限
 * post /o2o_service/role/v1/checkPermission
 * @param Env
 * @return true/false
 {
  "roleName": "管理员",
  "groupName": "商家管理",
  "permissionName": "添加商家",
  "act":1
  }
 */
api.checkPermission = function*(Env) {
    Env.I = yield F.Init(Env, [1]);
    if (Env.I.errors) {
        return F.returnMsg(400, Env.I.errors.msg, Env.I.errors.level);
    }
    var fields = Env.I;
    let result = yield roleDispatcher.checkPermission(fields);
    if (result.error) {
        return F.returnMsg(400, result.error, 3);
    } else {
        return F.returnMsg(200, 'OK', 3, result);
    }
};

/**
 * post /o2o_service/role/v1/checkMany
 {
    "roleName": "管理员",
    "permissions": [
        {"商家管理": ["添加商家","编辑商家"]},
        {"商家详情": ["评价管理"]},
        {"用户管理": ["交易管理"]},
        {"后台使用管理":["后台角色权限"]}
    ],
    "act": 1
 }
 * @param Env
 */
api.checkMany = function*(Env) {
    Env.I = yield F.Init(Env, [1]);
    if (Env.I.errors) {
        return F.returnMsg(400, Env.I.errors.msg, Env.I.errors.level);
    }
    var fields = Env.I;

    let result = yield roleDispatcher.checkMany(fields);
    if (result.error) {
        return F.returnMsg(400, result.error, 3);
    } else {
        return F.returnMsg(200, 'OK', 3, result);
    }
};
